using System;
using UnityEngine;

namespace DA.AnimGraph.Editor {

    [AGBatchTool("File", "全部导出")]
    public class Tool_Export : IAGBatchTool {
        public void Execute() {
            ExportAll();
        }

        public static void ExportAll() {
            // 先保存当前打开的文件再开始
            SaveEditingFile();
            // 开始全部导出
            var fileTool = AGEGlobal.GetInstance().fileTool;
            var fileList = fileTool.agaList;
            D.L($"[Export] 批量导出开始 文件数: {fileList.Count}");
            int skipNum = 0;
            int completeNum = 0;
            int failNum = 0;
            foreach (var file in fileList) {
                Export(file.path, true, ref completeNum, ref skipNum, ref failNum);
            }
            D.L($"[Export] 批量导出完成 成功: {completeNum}, 跳过: {skipNum}, 失败: {failNum}");
        }

        public static void SaveEditingFile() {
            var windows = AnimGraphEditorWindow.GetWindows();
            foreach (var window in windows) {
                window.SaveIfDirty();
            }
        }

        public static void Export(string path, bool skipIfNoPath, ref int completeNum, ref int skipNum, ref int failNum) {
            var c = new AGEContext(path, null);
            try {
                bool isSuccess;
                if (skipIfNoPath) {
                    isSuccess = c.BatchExport();
                } else {
                    c.ExportDry();
                    isSuccess = true;
                }
                if (isSuccess) completeNum += 1;
                else skipNum += 1;
            } catch (Exception e) {
                Debug.LogError($"{e}");
                failNum += 1;
            }
        }
    }

}
